package com.sea.finance.controller;

import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mchange.lang.DoubleUtils;
import com.sea.finance.entity.FreightTaxPredict;
import com.sea.finance.entity.PaymentIncreaseLoss;
import com.sea.finance.service.FreightTaxPredictService;
import com.sea.finance.service.PaymentIncreaseLossService;
import com.sea.supply.entity.BillRefused;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.NumberUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/sea/finance/freightTaxPredict")
public class FreightTaxPredictController {

    @Autowired
    private FreightTaxPredictService freightTaxPredictService;

    /**
     * 管理主页面
     * @param model
     * @return
     */
    @RequestMapping("/main")
    public String main(Model model) {

        return "/sea/finance/report/freightTaxPredict/main";
    }


    /**
     * 生成采购单
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/predict", method = RequestMethod.POST)
    public AjaxReturn produce(@RequestParam("freight")Double freight) {
        AjaxReturn result = Ajax.fail().setMsg("生成失败！");
        try{
            if (null != freight ) {
                freightTaxPredictService.predict(freight);
                result.setOk(true).setMsg("生成成功！");
            }
        }catch (RuntimeException e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByCnd")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     FreightTaxPredict freightTaxPredict) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<FreightTaxPredict> list = freightTaxPredictService.findByCnd(freightTaxPredict);
        PageInfo<FreightTaxPredict> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }

    @RequestMapping(value = "/export", method = RequestMethod.GET)
    @ResponseBody
    public void export(HttpServletResponse response, FreightTaxPredict freightTaxPredict) {
        List<FreightTaxPredict> list = freightTaxPredictService.findByCnd(freightTaxPredict);
        String[] title = {"渠道","SKU","产品名称", "最低含税价","最低不含税价","预估运费","预估关税","体积"};
        String fileName = "预估关税运费报表" + DateUtils.dateToString(new Date(), "yyyyMMdd") + ".xls";
        String sheetName = "预估关税运费报表";
        String[][] content = new String[list.size()][8];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            FreightTaxPredict obj = list.get(i);
            content[i][0] = obj.getProductChannelName();
            content[i][1] = obj.getProductSku();
            content[i][2] = obj.getProductName();
            content[i][3] = obj.getProductPriceCny()+"";
            content[i][4] = obj.getProductUnitPriceCny()+"";
            content[i][5] = obj.getProductFreight()+"";
            content[i][6] = obj.getProductTax()+"";
            content[i][7] = obj.getProductVolume()+"";
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}
